<template>
  <el-drawer custom-class="drawer-box" v-model="drawerData.show" :title="drawerData.title" :direction="direction" :before-close="handleClose" size="35%">
    <template #title>
      <span class="drawer-title">{{ drawerData.title }}</span>
    </template>
    <div class="form-box" v-if="drawerData.show">
      <el-form class="ruleFormRef" ref="ruleFormRef" :model="formData" :rules="rules" label-width="90px" style="width: 90%" label-position="right">
        <el-form-item v-for="item in customAttrList.data" :key="item.attr_id" :label="item.attr_name" :prop="item.prop" :label-width="item.attr_name.length >= 12 ? '200px' : '100px'">
          <el-input
            :disabled="drawerData.controlType == 'look'"
            v-if="item.attr_type == 'mobile' || item.attr_type == 'email' || item.attr_type == 'pca' || item.attr_type == 'textbox'"
            v-model="formData[item.prop]"
            :placeholder="`请输入${item.attr_name}`"
          ></el-input>
          <el-input :disabled="drawerData.controlType == 'look'" v-model="formData[item.prop]" v-if="item.system_code != 'remark_mobile' && item.attr_type == 'textarea'" type="textarea" :placeholder="`请输入${item.attr_name}`"></el-input>
          <el-input :disabled="drawerData.controlType == 'look'" v-model="formData[item.prop]" v-if="item.attr_type == 'textarea' && item.system_code == 'remark_mobile'" type="textarea" placeholder="如需输入多个手机号请用空格隔开"></el-input>
          <!-- 多选 -->
          <el-checkbox-group :disabled="drawerData.controlType == 'look'" v-model="formData[item.prop]" v-if="item.attr_type == 'muti_select'">
            <el-checkbox :disabled="drawerData.controlType == 'look'" v-for="it in item.attr_val" :key="it.val" :value="it.key" :label="it.key">{{ it.val }}</el-checkbox>
          </el-checkbox-group>
          <el-select :disabled="drawerData.controlType == 'look'" v-if="item.attr_type == 'select'" style="width: 100%" v-model="formData[item.prop]" :placeholder="`请选择${item.attr_name}`" :popper-append-to-body="false">
            <el-option v-for="it in item.attr_val" :key="it.val" :label="it.val" :value="it.key"></el-option>
          </el-select>
          <el-date-picker :disabled="drawerData.controlType == 'look'" value-format="YYYY-MM-DD" v-if="item.attr_type == 'date'" v-model="formData[item.prop]" type="date" :placeholder="`请输入${item.attr_name}`"></el-date-picker>
          <div :class="`upload-content ${drawerData.controlType == 'look' ? 'noEdit' : ''}`" v-if="item.attr_type == 'picture'">
            <el-upload action="none" v-if="!formData[item.prop]" @click="getUploadKey(item.prop)" :on-change="beforeAvatarUpload" accept=".jpg,.jpeg,.png,.JPG,.JPEG" :show-file-list="false" :limit="1" :auto-upload="false">
              <div class="upload-box">
                <img src="@/assets/image/content/add-icon.png" alt="" />
                <div>点击上传</div>
              </div>
            </el-upload>
            <div class="upload-file-box" v-else>
              <el-image style="width: 100%; height: 100%" :src="formData[item.prop]" fit="cover" />
              <el-icon @click="delFile(item.prop)" class="del"><Delete /></el-icon>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="btn-box">
      <el-button v-if="drawerData.controlType == 'look'" type="primary" @click="handleClose">返回</el-button>
      <blockquote v-else>
        <el-button v-if="drawerData.controlType != 'edit'" @click="initFormData">重置</el-button>
        <el-button type="primary" @click="saveFun">保存</el-button>
      </blockquote>
    </div>
  </el-drawer>
</template>

<script lang="ts" setup>
  import ZWUpload from '@/components/ZWUpload.vue'
  import { reactive, ref } from '@vue/reactivity'
  import { watch } from '@vue/runtime-core'
  import bus from '@/utils/bus'
  import { uploadFile2 } from '@/api/common'
  import { ElForm, ElMessage, ElSteps, UploadProps } from 'element-plus'
  import { createCustomer, getAttrList, customerShow, baseUpdate, custAttrList } from '@/api/customerCenter'
  // import { createCustomer, getAttrList, customerShow, baseUpdate } from '@/api/customerCenter'
  type FormInstance = InstanceType<typeof ElForm>
  const emit = defineEmits(['save'])
  const ruleFormRef: any = ref<FormInstance>()
  const props = defineProps(['sourceArr'])
  const canEditPhone = ref(true)
  const imgProps = ref([]) // 自定义图片prop
  let drawerData = ref({
    show: false,
    title: '添加客户',
    direction: 'rtl', //从右往左打开
    userInfo: {}, //查看
    controlType: 'create'
  })

  let formData: any = ref({})

  let validPhone = (rules: any, value: any, callback: any) => {
    let rex = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    if (!value) {
      callback(new Error('手机号不能为空'))
    } else if (!rex.test(value)) {
      callback(new Error('请输入正确的11位手机号码'))
    } else {
      callback()
    }
  }
  let validCustomPhone = (rules: any, value: any, callback: any) => {
    let rex = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    console.log(rules, value, 'validCustomPhone')

    if (value) {
      if (!rex.test(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    } else {
      callback()
    }
  }
  // 当前输入框有值才校验
  const validEmail = (rule: any, value: any, callback: any) => {
    let rex = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/
    if (value) {
      if (!rex.test(value)) {
        callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    } else {
      callback('邮箱不能为空')
    }
  }
  const validCustomEmail = (rule: any, value: any, callback: any) => {
    let rex = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/
    if (value) {
      if (!rex.test(value)) {
        callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    } else {
      callback()
    }
  }
  // 校验备用手机号
  const validRemarkMobile = (rule: any, value: string, callback: any) => {
    // 换行、中文【，】、英文【,】、均可分割
    const mobileValue = value.replace(/[,， \n]/g, ',')
    // 重复校验分组
    const mobileArr = mobileValue.split(',')
    console.log('mobileArr: ', mobileArr)
    const map = new Map()

    // 校验一个或者多个符合规则的手机号
    let reg = /^(1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8})(,(1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}))*$/
    if (!value) {
      callback()
    } else {
      if (!reg.test(mobileValue.trim())) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        for (const item of mobileArr) {
          if (map.get(item)) {
            return callback(new Error('手机号重复,请重新输入'))
          } else {
            map.set(item, item)
          }
        }
      }
    }
    callback()
  }

  // 删除图片
  const handleRemove = (ev, data) => {
    console.log(ev, data, 555)
  }

  let nowUploadKey = ''
  const getUploadKey = (key: string) => {
    // debugger
    nowUploadKey = key
  }

  // 上传图片的方法
  const uploadFun = (file: any, fileName: string, key: string) => {
    uploadFile2({
      file,
      fileName
    }).then((r: any) => {
      formData.value[nowUploadKey] = r.url
      console.log(formData.value[nowUploadKey])
      // 验证图片上传
      if (imgProps.value.length > 0) {
        imgProps.value.forEach((item) => {
          ruleFormRef.value.validateField([item])
        })
      }
    })
  }
  // 上传检验
  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any, key: string) => {
    // debugger
    console.log(rawFile, key, 5556)
    if (!rawFile) {
      return
    }
    if (rawFile.size / 1024 / 1024 > 10) {
      ElMessage.error('上传图片大小不能超过10M')
      return false
    }
    uploadFun(rawFile.raw, rawFile.name, key)
  }

  //
  const delFile = (key: string) => {
    formData.value[key] = ''
  }

  // 重置
  const initFormData = () => {
    ruleFormRef.value?.resetFields()
  }

  // 关闭
  const handleClose = () => {
    formAttrList.value = []
    customAttrList.data = []
    drawerData.value.show = false
  }

  const systemAttrList: any = [
    { attr_name: '姓名', attr_type: 'input', attr_val: [], code: 'name', key: 'name' },
    { attr_name: '手机号', attr_type: 'input', attr_val: [], code: 'mobile', key: 'mobile' },
    { attr_name: '性别', attr_type: 'select', attr_val: [], code: 'sex', key: 'sex' },
    { attr_name: '生日', attr_type: 'date', attr_val: '', code: 'birthday', key: 'birthday' },
    { attr_name: '年龄', attr_type: 'input', attr_val: [], code: 'age', key: 'age' },
    { attr_name: '备注', attr_type: 'input', attr_val: [], code: 'remark', key: 'remark' },
    { attr_name: '邮箱', attr_type: 'input', attr_val: [], code: 'email', key: 'email' },
    { attr_name: '学历', attr_type: 'select', attr_val: [], code: 'education', key: 'education' },
    { attr_name: '地址', attr_type: 'input', attr_val: [], code: 'address', key: 'address' },
    { attr_name: '微信号', attr_type: 'input', attr_val: [], code: 'wx_number', key: 'wx_number' },
    { attr_name: '头像', attr_type: 'picture', attr_val: [], code: 'avatar', key: 'avatar' },
    { attr_name: 'QQ', attr_type: 'input', attr_val: [], code: 'qq_number', key: 'qq_number' },
    { attr_name: '公司', attr_type: 'input', attr_val: [], code: 'company', key: 'company' },
    { attr_name: '年收入', attr_type: 'select', attr_val: [], code: 'income', key: 'income' },
    { attr_name: '区域', attr_type: 'input', attr_val: [], code: 'region', key: 'region' },
    { attr_name: '爱好', attr_type: 'input', attr_val: [], code: 'hobby', key: 'hobby' },
    { attr_name: '行业', attr_type: 'input', attr_val: [], code: 'industry', key: 'industry' },
    { attr_name: '客户来源', attr_type: 'select', attr_val: [], code: 'source', key: 'source' },
    { attr_name: '备用手机号', attr_type: 'textarea', attr_val: [], code: 'remark_mobile', key: 'remark_mobile' }
  ]

  let rules: any = ref({
    mobile: { required: true, validator: validPhone, trigger: 'blur' },
    name: { required: true, trigger: 'blur', message: '请输入客户姓名' },
    email: { trigger: 'blur', type: 'email', message: '请输入正确的邮箱' },
    source_id: { required: true, trigger: 'change', message: '请选择客户来源' },
    sex: { required: true, trigger: 'change', message: '请选择客户性别' },
    remark_mobile: [{ required: true, validator: validRemarkMobile, trigger: 'blur' }]
  })

  // 当前渲染的参数
  let formAttrList: any = ref([])
  let customAttrList: any = reactive({
    data: []
  })

  // 获取当前用户数据
  const customerShowFun = () => {
    //查看动态表单接口和查看表单值接口为同一接口，不要改！！！
    custAttrList({ cust_id: drawerData.value.userInfo.id }).then((r: any) => {
      r.custom_attr = r.custom_attr || []
      r.custom_attr.forEach((item: any) => {
        let key = 'form_attr_' + item.attr_id
        formData.value[key] = item.current_val ? item.current_val : ''
        if (item.attr_type == 'select') {
          const arr = item.attr_val.filter((jtem: any) => jtem.key == item.current_val)
          formData.value[key] = arr.length > 0 ? arr[0].key : ''
        }
      })
    })
  }

  // 获取创建客户属性列表
  const getAttrListFun = () => {
    custAttrList()
      .then((res: any) => {
        res.custom_attr.forEach((item: any) => {
          let key = 'form_attr_' + item.attr_id
          let val: any = ''
          if (item.attr_type == 'muti_select') {
            val = []
          }
          formData.value[key] = val
          if (item.system_code == 'source') {
            let arr = props.sourceArr.map((it: any) => {
              it.key = it.id || ''
              it.val = it.name || ''
              return it
            })
            arr.shift()
            item.attr_val = arr
          }
          const prefixMsg = ['textarea', 'textbox', 'mobile', 'email'].includes(item.attr_type) ? '请输入正确的' : ['select', 'muti_select', 'date', 'pca'].includes(item.attr_type) ? '请选择' : item.attr_type === 'picture' ? '请上传' : '请'
          if (item.is_required == 2) {
            rules.value[key] = [{ required: true, message: `${item.attr_name}不能为空`, trigger: ['change', 'blur'] }]
            if (['mobile', 'email'].includes(item.attr_type)) {
              rules.value[key].push({
                validator: item.attr_type == 'email' ? validEmail : validPhone
              })
            }
          } else {
            if (['mobile', 'email'].includes(item.attr_type)) {
              rules.value[key] = {
                validator: item.attr_type == 'email' ? validCustomEmail : validCustomPhone
              }
            } else if (item.system_code === 'remark_mobile') {
              rules.value[key] = {
                validator: validRemarkMobile
              }
            }
          }
          item.prop = key
          // 如果是上传图片
          if (item.attr_type == 'picture') {
            if (item.is_required == 2) {
              imgProps.value.push(key)
            }
            item.upInfo = {
              type: 1,
              label: '',
              prop: 'images',
              multiple: false,
              limitSize: 2,
              limitNum: 1,
              acceptFile: '.jpg,.jpeg,.png,.gif,.bmp,.pdf,.webp'
            }
          }
          customAttrList.data.push(item)
        })
        if (drawerData.value.userInfo.id) {
          customerShowFun()
        } else {
          canEditPhone.value = false
        }
      })
      .catch((e: object) => {
        console.log(e, 555)
        ElMessage.error('服务器开小差')
      })
  }

  watch(
    () => drawerData.value.show,
    (val: boolean) => {
      if (val) {
        formAttrList.value = []
        customAttrList.data = []
        drawerData.value.title = drawerData.value.controlType == 'create' ? '添加客户' : drawerData.value.controlType == 'edit' ? '编辑客户' : '查看客户'
        getAttrListFun()
      }
    }
  )

  // 获取上传的图片
  const getUploadData = (data: any, key: string) => {
    formData.value[key] = data[0] ? data[0].url : ''
  }

  // 保存
  const saveFun = () => {
    ruleFormRef.value.validate((valid: boolean, fileds: any) => {
      if (valid) {
        let { mobile, source_id } = formData.value
        let param: object = {
          mobile,
          source_id,
          system_attr: {},
          custom_attr: []
        }
        customAttrList.data.forEach((item: any) => {
          if (item.system_code == 'mobile') {
            param.mobile = formData.value[item.prop]
          }
          if (item.system_code == 'source') {
            param.source_id = formData.value[item.prop]
          }
          if (item.is_system) {
            param.system_attr[item.system_code] = formData.value[item.prop]
          } else {
            param.custom_attr.push({
              attr_id: item.attr_id,
              attr_name: item.attr_name,
              attr_type: item.attr_type,
              attr_val: formData.value[item.prop],
              is_system: item.is_system
            })
          }
        })
        if (drawerData.value.userInfo.id && drawerData.value.controlType == 'edit') {
          param.cust_id = drawerData.value.userInfo.id
          baseUpdate(param)
            .then((r: object) => {
              ElMessage.success('客户编辑成功')
              handleClose()
              emit('save', true)
            })
            .catch((e: object) => {})
          return
        }
        createCustomer(param)
          .then((r: object) => {
            ElMessage.success('客户创建成功')
            handleClose()
            emit('save', true)
          })
          .catch((e: object) => {})
      } else {
        console.log('error submit!')
        let rex = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/

        if (drawerData.value.controlType == 'edit' && formData.value['mobile'] && !rex.test(formData.value['mobile'])) {
          canEditPhone.value = false
        }
      }
    })
  }

  defineExpose({
    drawerData
  })
</script>

<style lang="scss" scoped>
  .drawer-box {
    position: relative;

    .form-box {
      position: absolute;
      top: 80px;
      left: 10px;
      bottom: 80px;
      width: 100%;
      overflow: auto;
      &::-webkit-scrollbar {
        display: none;
      }
      :deep(.el-form-item) {
        .el-form-item__content {
          .el-input {
            width: 100%;
          }
        }
      }
    }

    .btn-box {
      position: absolute;
      background: #fff;
      width: 100%;
      left: 0;
      bottom: 0;
      text-align: right;
      border-top: solid 1px #eee;
      padding: 20px;
    }
  }
  .upload-content {
    &.noEdit {
      pointer-events: none !important;

      .upload-box {
        background: lightgray;
        position: relative;
        &::after {
          content: '';
          width: 100%;
          height: 100%;
          background: lightgray;
          opacity: 0.6;
          position: absolute;
          top: 0;
          left: 0;
        }
      }
    }
    .upload-box {
      width: 110px;
      height: 110px;
      text-align: center;
      border-radius: 4px;
      background: #f8f8f8;
      border: 1px solid #eaeaea;
      box-sizing: border-box;
      padding-top: 28px;
      img {
        width: 20px;
        height: 20px;
      }
      div {
        width: 100%;
        line-height: 14px;
        font-size: 14px;
        font-family: STHeitiSC-Light, STHeitiSC;
        color: #ff6b00;
      }
    }
    .upload-file-box {
      position: relative;
      width: 110px;
      height: 110px;
      border-radius: 4px;
      border: 1px solid #eaeaea;
      overflow: hidden;
      .del {
        position: absolute;
        width: 15px;
        height: 15px;
        top: 5px;
        right: 5px;
        color: #e4e7ed;
      }
    }
    .upload-desc {
      font-size: 14px;
      font-family: STHeitiSC-Light, STHeitiSC;
      font-weight: 300;
      color: #969696;
      padding-top: 10px;
      span {
        color: #ff6b00;
        cursor: pointer;
      }
    }
  }
</style>
